
#include "OrderFile.h"
#include<fstream>
#include<string>
#include<vector>

using namespace std;

OrderFile::OrderFile(){
    ifstream ifs;
    ifs.open(ORDER_FILE,ios::in);

    vector<string> orderInfo{6};
    /*
    0    string date;        //日期
    1    string internal;    // 时间段
    2    string stuId;       // 学生ID
    3    string stuName;     // 学生姓名
    4    string roomId;      // 机房编号
    5   string status;      //预约状态
    */


    this->m_size=0;     //订单编号

    while(ifs>>orderInfo[0] && ifs>>orderInfo[1] && 
                ifs>> orderInfo[2]&& ifs>>orderInfo[3] && ifs>>orderInfo[4] && ifs>> orderInfo[5])
    {

        // code debug
        /*
        for(string info:orderInfo)
        {
        cout << info << endl;
        }
		*/

        string key;
        string value;
        map<string,string>m;

        for(string info:orderInfo)
        {
            int pos=info.find(":");
            if(pos!=-1)
            {
                key=info.substr(0,pos);
                value=info.substr(pos+1,info.size()-(pos+1));
                m.insert(make_pair(key,value));
            }
        }

        this ->m_orderData.insert(make_pair(this->m_size,m));
        this ->m_size++;

    }

    // debug code
    /*
    for (map<int, map<string, string>>::iterator it = m_orderData.begin(); it != m_orderData.end();it++)
	{
		cout << "key = " << it->first << " value = " << endl;
		for (map<string, string>::iterator mit = it->second.begin(); mit != it->second.end(); mit++)
		{
			cout << mit->first << " " << mit->second << " ";
		}
		cout << endl;
	}
    */
    
    ifs.close();

}

// 重写order.txt 信息
void OrderFile::updateOrder()
{
    if(this->m_size==0)
    {
        return;
    }
    // trunc 是就重写信息（删除原有信息，重写） 而且 out 默认就是trunc 
    ofstream ofs(ORDER_FILE,ios::out| ios::trunc);
    for(int i=0; i<(this->m_size);i++)
    {
        ofs<<"date:"<<this->m_orderData[i]["date"]<<" ";
        ofs<<"interval:"<<this->m_orderData[i]["interval"]<<" ";
        ofs<<"stuId:"<<this->m_orderData[i]["stuId"]<<" ";
        ofs<<"stuName:"<<this->m_orderData[i]["stuName"]<<" ";
        ofs<<"roomId:"<<this->m_orderData[i]["roomId"]<<" ";
        ofs<<"status:"<<this->m_orderData[i]["status"]<<endl;

    }
    ofs.close();
}

OrderFile::~OrderFile(){}